const fs=require('fs');
const request=require('request-promise');
const {spawn}=require('child_process');
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function init(){
    if (fs.existsSync('./chong.ts'))
    {
        fs.unlinkSync('./chong.ts');
    }

    if (fs.existsSync('./filelist.txt'))
    {
        fs.unlinkSync('./filelist.txt');
    }

    let mutxt=fs.readFileSync('./m3u8','utf-8');
    let txtArr=mutxt.split('\r\n');
    let index=0;
    
    let klist=[];
    for (let item of txtArr){
        if (item.substring(0,7)==='http://' || item.substring(0,8)==='https://'){
            klist.push(item);
        }
    }
    console.log(`共${klist.length}块`);
    
    for (let item of klist){
        let buf=await request({
            url:item,
            encoding:null
        }).catch((e)=>{
            console.log(e);
        })
        
        fs.writeFileSync(`./tmp${index}.ts`,buf,{
            flag:'a'
        })
        fs.writeFileSync(`./filelist.txt`,`file 'tmp${index}.ts'\r\n`,{
            flag:'a',
            encoding:'utf-8'
        })
        index++;
        console.log(`下载${index}块`);
    }

    console.log('ffmpeg合并');
    let margeTT=spawn('ffmpeg.exe',['-f','concat','-i','filelist.txt','-c','copy','chong.ts']);

    margeTT.stdout.on('data', function (data) {
        console.log('stdout: \r\n' + data);
    });
    
    margeTT.stderr.on('data', function (data) {
        console.log('stderr: \r\n' + data);
    });

    margeTT.on('exit', function (code) {
        console.log('程序退出' + code);
        
        for (let i=0;i<klist.length;i++){
            fs.unlinkSync(`./tmp${i}.ts`);
        }
        fs.unlinkSync('./filelist.txt');
    });
    
}



init();
